import { defineComponent, PropType, ref, Transition, watchEffect } from 'vue'
import './ActionSheet.less'

import { Option } from './type'

export default defineComponent({
	name: 'action-sheet',
	props: {
		show: {
			type: Boolean,
			default: false
		},
		title: String,
		options: {
			type: Array as PropType<Option[]>,
			default: () => []
		},
		cancelText: {
			type: String,
			default: '取消'
		},
		showCancel: {
			type: Boolean,
			default: false
		},
		select: {
			type: Function as PropType<(value: string | number) => void>,
			default: () => {}
		},
		unmount: {
			type: Function,
			default: () => {}
		}
	},
	// emits: ['update:show'],
	setup(props, { emit }) {
		const show = ref(false)

		watchEffect(() => {
			if (props.show) {
				setTimeout(() => {
					show.value = true
				}, 0)
			}
		})

		const afterLeave = () => {
			props.unmount()
		}

		const close = () => {
			show.value = false
			emit('update:show', false)
		}

		const select = (option: Option) => {
			props.select(option.value)
			if (option.stopClose) return
			close()
		}

		return () => {
			const options = () => (
				<div class="options">
					{props.options.map((option) => (
						<button
							type="button"
							class="option"
							disabled={option.disabeld}
							onClick={() => select(option)}
						>
							{option.label}
						</button>
					))}
				</div>
			)

			return (
				<div class="action-sheet">
					<Transition name="fade">
						<div
							v-show={show.value}
							class="action-sheet-mask"
							onClick={close}
						></div>
					</Transition>
					<Transition name="slide" onAfterLeave={afterLeave}>
						<div v-show={show.value} class="action-sheet-content">
							<div class="title" v-show={props.title}>
								{props.title}
							</div>
							{options()}
							<div v-show={props.showCancel} class="cancel" onClick={close}>
								{props.cancelText}
							</div>
						</div>
					</Transition>
				</div>
			)
		}
	}
})
